import requests, json
import time
import cv2
import os
import numpy as np

from keras.models import load_model

class AISERVER:
    def __init__(self):
        self._url = "https://2dzcx.cdpf.org.cn"
        self._session = requests.session()
        # self._session.adapters.DEFAULT_RETRIES = 2
        # self._session.headers['timeout'] = '30'
        self.headers = {
            "Host": "www.cdpf.org.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
            "Accept": "image/avif,image/webp,*/*",
            "Connection": "close"
        }
        # 加载保存的模型
        self.loaded_model = load_model('model.h5')

    def deelPic(self, id =1):
        try:
            response = self._session.get(self._url + "/cms/resource/ucode.jpg", headers=self.headers, timeout=30,
                                         verify=False)
            response.close()
        except:
            print('获取验证码超时')
            time.sleep(5)
            return 0
        picname = './AIimg/' + str(id) + ".jpg"
        if response.status_code == 200:
            with open(picname, "wb") as f:
                f.write(response.content)
                print("图片保存成功")
        else:
            print("图片下载失败")
            code = 0
            return code;
        self.removeBlack()
        yzm = self.gray(picname)
        return  yzm

    def removeBlack(self):
        # 读取图片
        image = cv2.imread('AIimg/1.jpg')
        #debug
        cv2.imwrite('AIimg/orign.jpg', image)
        # 将黑色部分替换为白色
        image[np.where((image == [0, 0, 0]).all(axis=2))] = [255, 255, 255]

        # 将红色部分保留，其余部分替换为白色
        lower_red = np.array([0, 0, 150])
        upper_red = np.array([100, 100, 255])
        mask = cv2.inRange(image, lower_red, upper_red)
        image[np.where(mask == 0)] = [255, 255, 255]

        cv2.imwrite('AIimg/1.jpg', image)


    def calculate_noise_count(self,img_obj, w, h):
        count = 0
        width, height = img_obj.shape
        for _w_ in [w - 1, w, w + 1]:
            for _h_ in [h - 1, h, h + 1]:
                if _w_ > width - 1:
                    continue
                if _h_ > height - 1:
                    continue
                if _w_ == w and _h_ == h:
                    continue
                if img_obj[_w_, _h_] < 230:  # 二值化的图片设置为255
                    count += 1
        return count

    def gray(self,name):
        image_path = name
        img = cv2.imread(image_path, 1)
        print("图片读取成功")
        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        k = 4
        w, h = gray_img.shape
        for _w in range(w):
            for _h in range(h):
                if _w == 0 or _h == 0:
                    gray_img[_w, _h] = 255
                    continue
                pixel = gray_img[_w, _h]
                if pixel == 255:
                    continue
                if self.calculate_noise_count(gray_img, _w, _h) < k:
                    gray_img[_w, _h] = 255

        blur = cv2.GaussianBlur(gray_img, (9, 9), 0)  # 高斯滤波降噪
        ret3, th3 = cv2.threshold(blur, 134, 255, 0)  # 二值化图片
        kernel = np.ones((3, 3), np.float32) # 腐蚀处理
        img_erode = cv2.erode(th3, kernel)
        # 创建输出文件夹
        output_folder = 'AIimg_gray'
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
        name = '1234.jpg'
        r = cv2.imwrite("AIimg_gray/" + name, img_erode)
        image = cv2.imread('AIimg_gray/' + name)
        cutname = []
        cutname.append(name[:1])
        cutname.append(name[1:2])
        cutname.append(name[2:3])
        cutname.append(name[3:4])
        # 获取图片的高度和宽度
        height, width = image.shape[:2]
        # 计算每一部分的宽度
        part_width = width // 4
        # 分割图片
        left = 5 #左平移
        right = part_width + 5
        for i in range(4):
            # 创建一个新的图片对象
            part = image[0:height, left:right]
            # 保存分割后的图片
            output_folder = 'AIimg/AIimg_cut/' + cutname[i]
            # if not os.path.exists(output_folder):
            #     os.makedirs(output_folder)
            # picname = time.time()
            cv2.imwrite(f'{output_folder}.jpg', part)
            # 更新left和right的值
            left = right
            right += part_width
        # print('图片垂直方向分割完成')
        # print(name)
        a = self.cnnPre('AIimg/AIimg_cut/1.jpg')
        b = self.cnnPre('AIimg/AIimg_cut/2.jpg')
        c = self.cnnPre('AIimg/AIimg_cut/3.jpg')
        d =self.cnnPre('AIimg/AIimg_cut/4.jpg')
        return f'{a}{b}{c}{d}'

    def cnnPre(self,path):
        imgsize = [105, 96]
        img = cv2.imread(path, cv2.IMREAD_COLOR)  # 读入图片
        img = cv2.resize(img, (imgsize[0], imgsize[1]))  # 设定图片像素维度
        image_array = np.array(img)  # 将图像转换为数组
        image_array = image_array / 255.0  # 对图像进行归一化处理，将像素值缩放到[0, 1]范围
        predictions = self.loaded_model.predict(np.expand_dims(image_array, axis=0))  # 将图像数组转换为模型所需的输入格式并进行预测
        max_value = np.max(predictions[0])
        predicted_class_index = np.argmax(predictions)
        list = ["2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N",
                "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        # print(list[predicted_class_index])
        return list[predicted_class_index]
